{% extends "前端/template.html" %}

{% block title %}
    锐眼识别 - 文字识别
{% endblock %}

{% block css %}
<style>
    .preview-container {
        width: 100%;
        min-height: 300px;
        border: 2px dashed #ccc;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        position: relative;
        overflow: hidden;
    }

    .preview-container.dragover {
        border-color: #696cff;
        background-color: rgba(105, 108, 255, 0.1);
    }

    .preview-image {
        max-width: 100%;
        max-height: 400px;
        display: none;
        cursor: pointer;
    }

    .preview-image:hover {
        opacity: 0.9;
    }

    .upload-text {
        text-align: center;
        color: #697a8d;
    }

    .upload-icon {
        font-size: 48px;
        color: #697a8d;
        margin-bottom: 10px;
    }

    #result-container {
        min-height: 300px;
        border: 1px solid #d9dee3;
        border-radius: 8px;
        padding: 1rem;
    }

    .result-text {
        white-space: pre-wrap;
        word-break: break-all;
    }

    .modal-body {
        padding: 1rem;
        background-color: #f5f5f9;
    }

    #modalPreviewImage {
        box-shadow: 0 0 10px rgba(0,0,0,0.1);
    }
</style>
{% endblock %}

{% block content %}
<div class="row">
    <!-- 左侧上传和预览区域 -->
    <div class="col-12 col-md-6 mb-4">
        <div class="card">
            <div class="card-header d-flex align-items-center justify-content-between">
                <h5 class="mb-0">图片上传与预览</h5>
            </div>
            <div class="card-body">
                <!-- 添加图片类型选择 -->
                <div class="mb-3">
                    <label class="form-label d-block">图片类型</label>
                    <div class="form-check form-check-inline">
                        <input class="form-check-input" type="radio" name="imageType" id="localType" value="local" checked>
                        <label class="form-check-label" for="localType">本地上传</label>
                    </div>
                    <div class="form-check form-check-inline">
                        <input class="form-check-input" type="radio" name="imageType" id="networkType" value="network">
                        <label class="form-check-label" for="networkType">网络上传</label>
                    </div>
                </div>
                
                <!-- 添加网络图片输入框 -->
                <div id="networkUrlInput" class="mb-3" style="display: none;">
                    <div class="input-group">
                        <input type="text" class="form-control" placeholder="请输入图片URL" id="imageUrl">
                        <button class="btn btn-outline-primary" type="button" id="previewNetworkImage">预览</button>
                    </div>
                </div>
                
                <!-- 修改本地上传区域的id -->
                <div id="localUploadArea">
                    <div class="preview-container" id="dropZone">
                        <img id="previewImage" class="preview-image" src="" alt="预览图片">
                        <div class="upload-placeholder">
                            <div class="text-center">
                                <i class="bx bx-image-add upload-icon"></i>
                                <p class="upload-text">
                                    拖拽图片到此处或
                                    <label for="imageInput" class="text-primary" style="cursor: pointer;">点击上传</label>
                                </p>
                            </div>
                        </div>
                        <input type="file" id="imageInput" accept="image/*" style="display: none;">
                    </div>
                </div>
                <div class="mb-3">
                    <label class="form-label d-block">回复方式</label>
                    <div class="form-check form-check-inline">
                        <input class="form-check-input" type="radio" name="responseType" id="directType" value="direct" checked>
                        <label class="form-check-label" for="directType">直接回复</label>
                    </div>
                    <div class="form-check form-check-inline">
                        <input class="form-check-input" type="radio" name="responseType" id="streamType" value="stream">
                        <label class="form-check-label" for="streamType">流式回复</label>
                    </div>
                </div>
                <div class="mt-3">
                    <button type="button" class="btn btn-primary" id="recognizeBtn" disabled>
                        <i class="bx bx-analyse me-1"></i>开始识别
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 右侧识别结果区域 -->
    <div class="col-12 col-md-6 mb-4">
        <div class="card">
            <div class="card-header d-flex align-items-center justify-content-between">
                <h5 class="mb-0">识别结果</h5>
                <button type="button" class="btn btn-icon btn-outline-primary btn-sm" id="copyBtn" disabled>
                    <i class="bx bx-copy"></i>
                </button>
            </div>
            <div class="card-body">
                <div id="result-container">
                    <p class="result-text" id="resultText">暂无识别结果</p>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 在 content block 的最后添加 Modal -->
<div class="modal fade" id="imagePreviewModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">图片预览</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body text-center">
                <img id="modalPreviewImage" src="" alt="预览图片" style="max-width: 100%; max-height: 70vh;">
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block js %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    const dropZone = document.getElementById('dropZone'); // 拖拽上传区域
    const imageInput = document.getElementById('imageInput'); // 上传图片按钮
    const previewImage = document.getElementById('previewImage'); // 预览图片
    const recognizeBtn = document.getElementById('recognizeBtn'); // 识别按钮
    const uploadPlaceholder = document.querySelector('.upload-placeholder'); // 上传提示
    const copyBtn = document.getElementById('copyBtn'); // 复制按钮
    const resultText = document.getElementById('resultText'); // 识别结果

    // 在 DOMContentLoaded 事件处理函数中添加一个全局变量来存储当前文件
    let currentFile = null;

    // 添加新的变量
    const networkUrlInput = document.getElementById('networkUrlInput');
    const localUploadArea = document.getElementById('localUploadArea');
    const imageUrl = document.getElementById('imageUrl');
    const previewNetworkImage = document.getElementById('previewNetworkImage');
    let currentImageUrl = null;

    // 添加 Modal 相关变量
    const imagePreviewModal = new bootstrap.Modal(document.getElementById('imagePreviewModal'));
    const modalPreviewImage = document.getElementById('modalPreviewImage');

    // 添加图片类型切换处理
    document.querySelectorAll('input[name="imageType"]').forEach(radio => {
        radio.addEventListener('change', (e) => {
            if (e.target.value === 'network') {
                networkUrlInput.style.display = 'block';
                localUploadArea.style.display = 'none';
                currentFile = null; // 清除本地文件
            } else {
                networkUrlInput.style.display = 'none';
                localUploadArea.style.display = 'block';
                currentImageUrl = null; // 清除网络图片URL
            }
            // 重置预览和按钮状态
            previewImage.style.display = 'none';
            uploadPlaceholder.style.display = 'block';
            recognizeBtn.disabled = true;
            resultText.textContent = '暂无识别结果';
            copyBtn.disabled = true;
        });
    });

    // 修改网络图片预览功能
    previewNetworkImage.addEventListener('click', () => {
        const url = imageUrl.value.trim();
        if (!url) {
            showToast('请输入图片URL', 'warning');
            return;
        }

        // 预览网络图片
        previewImage.src = url;
        modalPreviewImage.src = url; // 设置 Modal 中的图片
        previewImage.style.display = 'block';
        uploadPlaceholder.style.display = 'none';
        currentImageUrl = url;
        recognizeBtn.disabled = false;
        
        // 显示预览 Modal
        imagePreviewModal.show();
    });

    // 为预览图片添加点击事件，点击时显示大图
    previewImage.addEventListener('click', () => {
        if (previewImage.style.display !== 'none') {
            modalPreviewImage.src = previewImage.src;
            imagePreviewModal.show();
        }
    });

    // 拖拽上传
    dropZone.addEventListener('dragover', (e) => {
        e.preventDefault();
        dropZone.classList.add('dragover');
    });

    dropZone.addEventListener('dragleave', (e) => {
        e.preventDefault();
        dropZone.classList.remove('dragover');
    });

    dropZone.addEventListener('drop', (e) => {
        e.preventDefault();
        dropZone.classList.remove('dragover');
        const files = e.dataTransfer.files;
        if (files.length > 0) {
            handleImageFile(files[0]);
        }
    });

    // 点击上传
    imageInput.addEventListener('change', (e) => {
        if (e.target.files.length > 0) {
            handleImageFile(e.target.files[0]);
        }
    });

    // 修改 handleImageFile 函数
    function handleImageFile(file) {
        if (!file.type.startsWith('image/')) {
            showToast('请上传图片文件！', 'warning');
            return;
        }

        currentFile = file;
        const reader = new FileReader();
        reader.onload = (e) => {
            previewImage.src = e.target.result;
            modalPreviewImage.src = e.target.result; // 设置 Modal 中的图片，但不显示
            previewImage.style.display = 'block';
            uploadPlaceholder.style.display = 'none';
            recognizeBtn.disabled = false;
            
            // 移除自动显示预览 Modal
            // imagePreviewModal.show();
        };
        reader.readAsDataURL(file);
    }

    // 修改识别按钮点击事件
    recognizeBtn.addEventListener('click', async () => {
        const imageType = document.querySelector('input[name="imageType"]:checked').value;
        const responseType = document.querySelector('input[name="responseType"]:checked').value;
        
        if (imageType === 'local' && !currentFile) {
            showToast('请先选择图片', 'warning');
            return;
        }
        
        if (imageType === 'network' && !currentImageUrl) {
            showToast('请先输入并预览图片', 'warning');
            return;
        }

        recognizeBtn.disabled = true;
        resultText.textContent = "正在处理...";
        showLoading("正在处理...");

        try {
            // 获取用户信息
            const userInfo = JSON.parse(sessionStorage.getItem('userInfo') || localStorage.getItem('userInfo'));
            if (!userInfo || !userInfo.user_id) {
                hideLoading();
                showToast('请先登录', 'warning');
                setTimeout(() => {
                    window.location.href = '/login/';
                }, 1500);
                return;
            }

            let image_id;
            
            if (imageType === 'local') {
                // 本地上传流程
                const formData = new FormData();
                formData.append('image', currentFile);
                formData.append('user_id', userInfo.user_id);

                const uploadResponse = await axios.post('/api/upload_image/', formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                });

                if (uploadResponse.data.code !== 200) {
                    throw new Error(uploadResponse.data.message || '上传失败');
                }
                
                image_id = uploadResponse.data.data.image_id;
            } else {
                // 网络图片直接使用URL
                image_id = currentImageUrl;
            }

            if (responseType === 'stream') {
                // 流式响应处理
                resultText.textContent = ''; // 清空结果
                showLoading("正在解析图片...");  // 显示 loading
                
                try {
                    // 创建 EventSource 连接
                    const url = `/api/v2/img_to_text/?image_id=${image_id}&image_type=${imageType}`;
                    const eventSource = new EventSource(url);
                    
                    let firstResponse = true;  // 添加标记，用于判断是否是第一次收到响应
                    
                    // 处理消息
                    eventSource.onmessage = (event) => {
                        if (event.data === '[DONE]') {
                            eventSource.close();
                            copyBtn.disabled = false;
                            showToast('识别完成', 'success');
                            // 重置图片预览状态
                            resetImagePreview();
                        } else if (event.data === '正在解析') {
                            resultText.textContent = '';
                        } else {
                            if (firstResponse) {  // 第一次收到响应时
                                hideLoading();    // 隐藏 loading
                                firstResponse = false;
                            }
                            resultText.textContent += event.data;
                        }
                    };
                    
                    // 处理错误
                    eventSource.onerror = (error) => {
                        console.error('EventSource failed:', error);
                        eventSource.close();
                        hideLoading();  // 确保出错时也隐藏 loading
                        throw new Error('流式请求失败');
                    };
                    
                } catch (error) {
                    hideLoading();  // 确保出错时也隐藏 loading
                    throw error;
                }
            } else {
                // 直接响应处理
                const recognizeResponse = await axios.post('/api/v1/img_to_text/', {
                    image_id: image_id,
                    image_type: imageType
                });

                if (recognizeResponse.data.code === 200) {
                    resultText.textContent = recognizeResponse.data.data;
                    copyBtn.disabled = false;
                    hideLoading();
                    showToast('识别成功', 'success');
                    // 重置图片预览状态
                    resetImagePreview();
                } else {
                    throw new Error(recognizeResponse.data.message || '识别失败');
                }
            }
        } catch (error) {
            console.error('处理失败:', error);
            resultText.textContent = "处理失败: " + (error.message || '未知错误');
            hideLoading();
            showToast(error.message || '处理失败', 'error');
        } finally {
            recognizeBtn.disabled = false;
        }
    });

    // 添加复制文本的辅助函数
    function copyTextToClipboard(text) {
        // 创建临时文本区域
        const textArea = document.createElement('textarea');
        textArea.value = text;
        
        // 设置样式使其不可见
        textArea.style.position = 'fixed';
        textArea.style.top = '0';
        textArea.style.left = '0';
        textArea.style.width = '2em';
        textArea.style.height = '2em';
        textArea.style.padding = '0';
        textArea.style.border = 'none';
        textArea.style.outline = 'none';
        textArea.style.boxShadow = 'none';
        textArea.style.background = 'transparent';
        
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();
        
        try {
            // 尝试使用新API
            if (navigator.clipboard && window.isSecureContext) {
                return navigator.clipboard.writeText(text);
            }
            
            // 使用document.execCommand
            const successful = document.execCommand('copy');
            if (!successful) {
                throw new Error('复制失败');
            }
            return Promise.resolve();
        } catch (err) {
            return Promise.reject(err);
        } finally {
            // 清理
            document.body.removeChild(textArea);
        }
    }

    // 修改复制按钮点击事件
    copyBtn.addEventListener('click', () => {
        const textToCopy = resultText.textContent;
        copyTextToClipboard(textToCopy)
            .then(() => {
                showToast('复制成功！', 'success');
            })
            .catch(err => {
                console.error('复制失败：', err);
                showToast('复制失败，请手动复制', 'error');
            });
    });

    // 添加重置图片预览的函数
    function resetImagePreview() {
        // 清空预览图片
        previewImage.src = '';
        previewImage.style.display = 'none';
        modalPreviewImage.src = '';
        
        // 显示上传占位符
        uploadPlaceholder.style.display = 'block';
        
        // 重置文件和URL
        currentFile = null;
        currentImageUrl = null;
        
        // 清空网络图片URL输入框
        imageUrl.value = '';
        
        // 禁用识别按钮
        recognizeBtn.disabled = true;
    }
});
</script>
{% endblock %}

{% block nav_left %}
{% include "前端/components/左侧导航栏.html" %}
{% endblock %}

{% block NavBar %}
{% include "前端/components/搜索框、个人头像.html" %}
{% endblock %}

{% block footer %}
{% include "前端/components/Footer.html" %}
{% endblock %}